package com.hmy.equipment.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.hmy.equipment.domain.HmyEquipment;
import com.hmy.equipment.mapper.HmyEquipmentMapper;
import com.hmy.equipment.service.HmyEquipmentService;
import com.hmy.pig.domain.HmyPig;
import com.ruoyi.common.security.utils.PigUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

/**
 * @Author ljy
 * @Date 2024/2/22 11:15
 * @description:
 * @Title: HmyEquipmentServiceImpl
 * @Package com.hmy.equipment.service.impl
 */
@Service
public class HmyEquipmentServiceImpl implements HmyEquipmentService {
    @Resource
    private HmyEquipmentMapper hmyEquipmentMapper;

    @PostConstruct
    public void init(){
        loadingEquipmentDataCache();
    }

    private void loadingEquipmentDataCache() {
        List<HmyEquipment> list = hmyEquipmentMapper.findList(null);
        HashMap<String, List<HmyEquipment>> map = new HashMap<>();
        for (HmyEquipment hmyEquipment : list) {
            if (map.containsKey(hmyEquipment.getEquipmentPhouseCode())){
                map.get(hmyEquipment.getEquipmentPhouseCode()).add(hmyEquipment);
            }else {
                List<HmyEquipment> list1 = new ArrayList<>();
                list1.add(hmyEquipment);
                map.put(hmyEquipment.getEquipmentPhouseCode(),list1);
            }
        }
        PigUtils.setEquipmentCache(map);
    }

    @Override
    public List<HmyEquipment> findList(HmyEquipment hmyEquipment) {
        List<HmyEquipment> list = new ArrayList<>();
        if (Objects.isNull(hmyEquipment.getEquipmentPhouseCode())){
            List<Object> cacheAll = PigUtils.getEquipmentAll();
            for (Object o : cacheAll) {
                list.add(JSONObject.parseObject(String.valueOf(o), HmyEquipment.class));
            }
            return list;
        }else {
            List<Object> cacheByCode = PigUtils.getEquipmentCacheByCode(hmyEquipment.getEquipmentPhouseCode());
            for (Object o : cacheByCode) {
                list.add(JSONObject.parseObject(String.valueOf(o), HmyEquipment.class));
            }
        }
        return list;
    }
}
